package us.congcong.jhostsmanager.utils;

import java.io.File;
import java.io.IOException;

import org.apache.commons.lang3.SystemUtils;

import us.congcong.jhostsmanager.HostsEditor;

public class HostsUtil {
	public static String getHostsContent(){
		String fileName = null;
		String fileContent = "";
		
		if(SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_UNIX){
			fileName = "/etc/hosts";
		} else if(SystemUtils.IS_OS_WINDOWS){
			fileName = "C:\\Windows\\System32\\drivers\\etc\\hosts";
		} else {
			return "未知系统";
		}
		
		try {
			File file = new File(fileName);
			fileContent = org.apache.commons.io.FileUtils.readFileToString(file, "UTF-8");
		} catch (IOException e) {
		 e.printStackTrace();
		}
		return fileContent;
    }
    
	public static Boolean saveHostsContent(String fileContent){
		File file = HostsUtil.getHostsFile();
		
		if(file == null){
			return false;
		} else {
			try {
				 org.apache.commons.io.FileUtils.writeStringToFile(file, fileContent, "UTF-8");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return true;
		}
    }
    
	public static File getHostsFile(){
    	String fileName = null;
    	if(SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC){
			fileName = "/etc/hosts";
			return new File(fileName);
		} else if(SystemUtils.IS_OS_WINDOWS){
			fileName = "C:\\Windows\\System32\\drivers\\etc\\hosts";
			return new File(fileName);
		} else {
			System.out.println("未知系统");
			return null;
		}
    }
}
